﻿using HuiZe.education.Common;
using HuiZe.education.Resource.Controls;
using HuiZe.education.ViewModel;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace HuiZe.education.View
{
    /// <summary>
    /// ShowQQLogin.xaml 的交互逻辑
    /// </summary>
    public partial class ShowQQLogin : Window
    {
        public int LoadType { get; set; }
        FormsWebBrowser formsWebBrowser = null;
        Window _owner;
        FrameworkElement _placementTarget;
        System.Windows.Forms.Form _form;
     public    System.Windows.Forms.WebBrowser _wb = new System.Windows.Forms.WebBrowser();

        public System.Windows.Forms.WebBrowser WebBrowser { get { return _wb; } }
        public string loadUrl { get; set; }
        public ShowQQLogin()
        {
            InitializeComponent();

            _wb.ScriptErrorsSuppressed = true;
            Loaded += AccountLoginView_Loaded;

            //this.Left = 3500;// -LeftEx;
            //this.Top = 600;// -TopEx;
        }

        private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {

            try
            {
                // ((System.Windows.Forms.WebBrowser)sender).Document.Window.Error +=  new HtmlElementErrorEventHandler(Window_Error);

                if (WebBrowser.Url.OriginalString.ToString().Contains("code=")&& WebBrowser.Url.OriginalString.ToString().Contains("setting"))
                {
                    
                    if (LoadType == 1)
                    {
                        string query = WebBrowser.Url.OriginalString.ToString();
                        string code = query.Substring(query.IndexOf("code=") + 5, query.IndexOf("&state") - (query.IndexOf("code=") + 5));
                        string state = query.Substring(query.IndexOf("state=") + 6, query.Length - (query.IndexOf("state=") + 6));
                        PersonCenterViewModel PersonViewModel = DataContext as PersonCenterViewModel;
                        PersonViewModel.QQLogin(code, state);
                        PersonViewModel.GetLoginInfo();
                        formsWebBrowser.Close();
                        this.Close();
                        
                    }
                    else if (LoadType ==3)
                    {
                        string query = WebBrowser.Url.OriginalString.ToString();
                        string code = query.Substring(query.IndexOf("code=") + 5, query.IndexOf("&state") - (query.IndexOf("code=") + 5));
                        string state = query.Substring(query.IndexOf("state=") + 6, query.Length - (query.IndexOf("state=") + 6));
                        PersonCenterViewModel PersonViewModel = DataContext as PersonCenterViewModel;
                        PersonViewModel.WXLogin(code, state);
                        PersonViewModel.GetLoginInfo();
                        formsWebBrowser.Close();
                        this.Close();
                        
                    }
                    else if (LoadType == 4)
                    {
                        string query = WebBrowser.Url.OriginalString.ToString();
                        string code = query.Substring(query.IndexOf("code=") + 5, query.IndexOf("&state") - (query.IndexOf("code=") + 5));
                        string state = query.Substring(query.IndexOf("state=") + 6, query.Length - (query.IndexOf("state=") + 6));
                        LoginViewModel loginViewModel = DataContext as LoginViewModel;
                        loginViewModel.QQLogin(code, state);
                        formsWebBrowser.Close();
                        this.Close();

                    }

                    //if (LoadType == 2)
                    //{
                    //    string query = WebBrowser.Url.OriginalString.ToString();
                    //    string code = query.Substring(query.IndexOf("code=") + 5, query.IndexOf("&state") - (query.IndexOf("code=") + 5));
                    //    string state = query.Substring(query.IndexOf("state=") + 6, query.Length - (query.IndexOf("state=") + 6));
                    //    LoginViewModel loginViewModel = DataContext as LoginViewModel;
                    //    loginViewModel.WXLogin(code, state);

                    //    formsWebBrowser.Close();
                    //    this.Close();


                    //}

                }
                else if (WebBrowser.Url.OriginalString.ToString().Contains("code="))
                {
                    if (LoadType == 1)
                    {
                        string query = WebBrowser.Url.OriginalString.ToString();
                        string code = query.Substring(query.IndexOf("code=") + 5, query.IndexOf("&state") - (query.IndexOf("code=") + 5));
                        string state = query.Substring(query.IndexOf("state=") + 6, query.Length - (query.IndexOf("state=") + 6));
                        LoginViewModel loginViewModel = DataContext as LoginViewModel;
                        loginViewModel.QQLogin(code, state);

                        formsWebBrowser.Close();
                        this.Close();


                    }

                    if (LoadType == 2)
                    {
                        string query = WebBrowser.Url.OriginalString.ToString();
                        string code = query.Substring(query.IndexOf("code=") + 5, query.IndexOf("&state") - (query.IndexOf("code=") + 5));
                        string state = query.Substring(query.IndexOf("state=") + 6, query.Length - (query.IndexOf("state=") + 6));
                        LoginViewModel loginViewModel = DataContext as LoginViewModel;
                        loginViewModel.WXLogin(code, state);
                      
                        formsWebBrowser.Close();
                        this.Close();
                        

                    }

                }
                var a = WebBrowser.Document.Body.Children;






            }
            catch { }



        }

        private void AccountLoginView_Loaded(object sender, System.Windows.RoutedEventArgs e)
        {
            //this.Left =900;
            //this.Top = 300;
            //Window owner = this; ;
            //WebControl webControl = new WebControl
            //{

            //};
            //webControl.ShowDialog();
            //this.webBrowserDockPanel.Children.Add(webControl);
            //webControl.web_browser.Navigate(loadUrl);
            //WebBrowserOverlay webBrowserOverlay = new WebBrowserOverlay(this.webBrowserDockPanel);

            //webBrowserOverlay.Width = 700;
            //webBrowserOverlay.Height = 400;
            //webBrowserOverlay.WebBrowser.Navigate(new Uri(loadUrl));
            //DockPanelWebBrowser.Navigate(new Uri(loadUrl));
            //DockPanelWebBrowser.Navigate(loadUrl);
            formsWebBrowser = new FormsWebBrowser(this.webBrowserDockPanel, this); //或者直接this
            _wb = formsWebBrowser.WebBrowser;
            formsWebBrowser.WebBrowser.DocumentCompleted += webBrowser1_DocumentCompleted;
            formsWebBrowser.WebBrowser.Navigate(new Uri(loadUrl));
            //_placementTarget = this.webBrowserDockPanel;

            // _owner = owner;
            //_form = new Form();
            //_form.Opacity =50;
            //_form.ShowInTaskbar = false;
            //_form.FormBorderStyle = FormBorderStyle.None;
            //_wb.Dock = DockStyle.Fill;
            //_form.Controls.Add(_wb);

            //owner.LocationChanged += delegate { OnSizeLocationChanged(); };
            //_placementTarget.SizeChanged += delegate { OnSizeLocationChanged(); };

            //if (owner.IsVisible)
            //    InitialShow();
            //else
            //    owner.SourceInitialized += delegate
            //    {
            //        InitialShow();
            //    };

            //DependencyPropertyDescriptor dpd = DependencyPropertyDescriptor.FromProperty(UIElement.OpacityProperty, typeof(Window));
            //dpd.AddValueChanged(owner, delegate { _form.Opacity = _owner.Opacity; });

            //_form.FormClosing += delegate { _owner.Close(); };

            //_wb.Navigate(loadUrl);

            //_placementTarget = this.webBrowserDockPanel;
            //Window owner = this;
            ////Window owner = mainWindow; //page中传入window
            ////Debug.Assert(owner != null);
            //_owner = owner;

            //_form = new System.Windows.Forms.Form();
            //_form.Opacity = owner.Opacity;
            //_form.ShowInTaskbar = false;
            //_form.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
            //_wb.Dock = System.Windows.Forms.DockStyle.Fill;
            //_form.Controls.Add(_wb);

            //owner.LocationChanged += delegate { OnSizeLocationChanged(); };
            //_placementTarget.SizeChanged += delegate { OnSizeLocationChanged(); };

            //if (owner.IsVisible)
            //    InitialShow();
            //else
            //    owner.SourceInitialized += delegate
            //    {
            //        InitialShow();
            //    };

            //System.ComponentModel.DependencyPropertyDescriptor dpd = System.ComponentModel.DependencyPropertyDescriptor.FromProperty(UIElement.OpacityProperty, typeof(Window));
            //dpd.AddValueChanged(owner, delegate { _form.Opacity = _owner.Opacity; });

            //_form.FormClosing += delegate { _owner.Close(); };
            //msgDetail2.Visibility = Visibility.Visible;
        }
        System.Windows.Threading.DispatcherOperation _repositionCallback;
        void InitialShow()
        {
            System.Windows.Forms.NativeWindow owner = new System.Windows.Forms.NativeWindow();
            owner.AssignHandle(((System.Windows.Interop.HwndSource)System.Windows.Interop.HwndSource.FromVisual(_owner)).Handle);
            _form.Show(owner);
            owner.ReleaseHandle();
        }
        void OnSizeLocationChanged()
        {
            if (_repositionCallback == null)
                _repositionCallback = _owner.Dispatcher.BeginInvoke(new Action(Reposition), System.Windows.Threading.DispatcherPriority.Input);
        }

        void Reposition()
        {
            _repositionCallback = null;

            Point offset = _placementTarget.TranslatePoint(new Point(), _owner);
            Point size = new Point(_placementTarget.ActualWidth, _placementTarget.ActualHeight);
            System.Windows.Interop.HwndSource hwndSource = (System.Windows.Interop.HwndSource)System.Windows.Interop.HwndSource.FromVisual(_owner);
            CompositionTarget ct = hwndSource.CompositionTarget;
            offset = ct.TransformToDevice.Transform(offset);
            size = ct.TransformToDevice.Transform(size);

            Win32.POINT screenLocation = new Win32.POINT(offset);
            Win32.ClientToScreen(hwndSource.Handle, ref screenLocation);
            Win32.POINT screenSize = new Win32.POINT(size);

            Win32.MoveWindow(_form.Handle, screenLocation.X, screenLocation.Y, screenSize.X, screenSize.Y, true);
        }

        private void exitAddStu_Click2(object sender, RoutedEventArgs e)
        {
            this.Close();
        }
    }

    static class Win32
    {
        [System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Sequential)]
        public struct POINT
        {
            public int X;
            public int Y;

            public POINT(int x, int y)
            {
                this.X = x;
                this.Y = y;
            }
            public POINT(Point pt)
            {
                X = Convert.ToInt32(pt.X);
                Y = Convert.ToInt32(pt.Y);
            }
        };

        [System.Runtime.InteropServices.DllImport("user32.dll")]
        internal static extern bool ClientToScreen(IntPtr hWnd, ref POINT lpPoint);

        [System.Runtime.InteropServices.DllImport("user32.dll")]
        internal static extern bool MoveWindow(IntPtr hWnd, int X, int Y, int nWidth, int nHeight, bool bRepaint);

    }
    //private void exitAddStu_Click2(object sender, RoutedEventArgs e)
    //    {
            //if (formsWebBrowser != null)
            //{
            //    formsWebBrowser.Close();

            //}
            //this.webBrowserDockPanel.Children.Clear();
            //msgDetail2.Visibility = Visibility.Collapsed;
        //}

    //}
}
